package br.com.JZSolution.domineduplex.gui;

import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import br.com.JZSolution.domineduplex.DomineDuplex;
import br.com.JZSolution.domineduplex.controle.ControladorDeUsuario;
import br.com.JZSolution.domineduplex.gui.dialogos.AdicionarContatoDialogo;
import br.com.JZSolution.domineduplex.gui.images.LeitorDeImagem;
import br.com.JZSolution.domineduplex.rede.ControladorDeEnvio;
import br.com.JZSolution.domineduplexserver.modelo.Usuario;

public class PainelContatos extends JPanel {

	private JList jListContatos;
	private JPopupMenu popup;
	private DefaultListModel dlm = new DefaultListModel();
	private boolean direitoPressionado = false;
	public PainelContatos(){
		super(new BorderLayout());
		
		JLabel contact = new JLabel("Contatos");
		
		JButton btnAdd = new JButton(LeitorDeImagem.getInstance().carregarImagem("plus.png"));
		btnAdd.setToolTipText("Adicionar contato");
		btnAdd.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				new AdicionarContatoDialogo();
				
			}
		});
		JPanel painelAddContato = new JPanel(new BorderLayout(0,0));
		painelAddContato.setBorder(BorderFactory.createLineBorder(Color.GRAY));
		painelAddContato.add(btnAdd,BorderLayout.EAST);
		painelAddContato.add(contact,BorderLayout.CENTER);
		jListContatos = new JList(dlm);
		jListContatos.setCellRenderer(new NossoListCellRenderer());
		jListContatos.addMouseListener(new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent e) {
				if (SwingUtilities.isRightMouseButton(e)) {
					try {
						Robot robot = new Robot();
						robot.mousePress(InputEvent.BUTTON1_MASK);
						robot.mouseRelease(InputEvent.BUTTON1_MASK);
						direitoPressionado = true;
					} catch (AWTException ae) {
						
					}
				}
				
			}
			
			@Override
			public void mouseReleased(MouseEvent e) {
				if(direitoPressionado) {
					jListContatos.setSelectedIndex( jListContatos.locationToIndex(e.getPoint()) );
					Usuario usr = (Usuario)jListContatos.getSelectedValue();
					direitoPressionado = false;
					mostrarPopupOpcoes(e,usr);
				}
			}
			
			@Override
			public void mouseClicked(MouseEvent e) {
				if(e.isPopupTrigger()) {
					jListContatos.setSelectedIndex( jListContatos.locationToIndex(e.getPoint()) );
					Usuario usr = (Usuario)jListContatos.getSelectedValue();
					mostrarPopupOpcoes(e,usr);
				}
			}
		});
		
		jListContatos.addListSelectionListener(new ListSelectionListener() {
			
			@Override
			public void valueChanged(ListSelectionEvent e) {
			    if (e.getValueIsAdjusting() == false) {
			    	
			        if (jListContatos.getSelectedIndex() > -1) {
			        	System.out.println("Value Chanage");
			        }
			    }
			}
		});
		

		this.add(painelAddContato,BorderLayout.NORTH);
		this.add(new JScrollPane(jListContatos,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED),BorderLayout.CENTER);
		
	}
	
	public JList getJListContatos() {
		return jListContatos;
	}
	
	public void  atualizarContatos(List<Usuario> listaDeUsuario){
		dlm.removeAllElements();
		for(Usuario usr :listaDeUsuario){
			dlm.addElement(usr);
		}
		atualizarListaContatos();
	}
	
	private void mostrarPopupOpcoes(MouseEvent e,final Usuario usr){
		popup = new JPopupMenu();
		JMenuItem nome = new JMenuItem(usr.getEmail());
		nome.setIcon(LeitorDeImagem.getInstance().carregarImagem("contato.png"));
		nome.setSelected(false);
		
		JMenuItem enviarArq = new JMenuItem("Enviar arquivo");
		enviarArq.setIcon(LeitorDeImagem.getInstance().carregarImagem("sendPeq.png"));
		enviarArq.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
			
				JFileChooser escolherArquivo = new JFileChooser(DomineDuplex.getUltimoPath());
				File arquivoParaEnviar = null;
		        int returnVal = escolherArquivo.showDialog(DomineDuplex.getInstance().getMainframe(), "Abrir");
		        
		        if (returnVal == JFileChooser.APPROVE_OPTION) {
		        	arquivoParaEnviar = escolherArquivo.getSelectedFile();
		        	DomineDuplex.setUltimoPath(arquivoParaEnviar.getParent() + "/");
		        	new ControladorDeEnvio(usr.getIp(), usr.getPorta(), arquivoParaEnviar);
		        } 
		        
				popup.setVisible(false);
			}
		});
		
		JMenuItem removerContato = new JMenuItem("Remover contato ");
		removerContato.setIcon(LeitorDeImagem.getInstance().carregarImagem("remover.png"));
		removerContato.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				ControladorDeUsuario.getInstance().removerContato(usr);
			}
		});
		
		//popup.add(nome);
		popup.add(enviarArq);
		popup.add(removerContato);
		popup.show(e.getComponent(), e.getX(), e.getY());
	}
	
	private class NossoListCellRenderer extends DefaultListCellRenderer {
		
		public NossoListCellRenderer(){
			setOpaque(true);
		}
		
		@Override
		public Component getListCellRendererComponent(JList list, Object value,
				int index, boolean isSelected, boolean cellHasFocus) {
			super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
	      	Usuario usr = (Usuario) value;
	        setText(" "+usr.getEmail());
			return this;
		}
		
	}
	
	public void adicionarContato(Usuario usr){
		dlm.addElement(usr);
		atualizarListaContatos();
	}
	
	public void removerContato(Usuario usr){
		dlm.removeElement(usr);
		atualizarListaContatos();
	}
	public void atualizarListaContatos(){
		jListContatos = new JList(dlm);
		this.jListContatos.setCellRenderer(new NossoListCellRenderer());
	}
	public void limparListaContatos() {
		dlm.removeAllElements();
	}
	
}
